﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using CRM.Anyleads.ResponseStruct;
using CRM.Extensions;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace CRM.Models.GlobalSearch
{
    /// <summary>
    /// 域名搜索结果缓存表
    /// </summary>
    [Index(nameof(UrlHashCode))]
    [Index(nameof(DomainHashCode))]
    public class KeywordsDomain : BaseModel
    {
        private string _title;
        private string _url;
        public int Id { get; set; }
        
        public string Url
        {
            get => _url;
            set
            {
                _url = value;
                UrlHashCode = value.GetFixedHashCode();
                Domain = new Uri(value).Host;
                DomainHashCode = Domain.GetFixedHashCode();
            }
        }
        
        public long UrlHashCode { get; private set; }

        [MaxLength(100)] public string Domain { get; private set; }
        public long DomainHashCode { get; private set; }

        public string Description { get; set; }

        [MaxLength(255)]
        public string Title
        {
            get => _title;
            set
            {
                _title = value;
                TitleLowercase = value.ToLower();
            }
        }

        [MaxLength(255)] public string TitleLowercase { get; private set; }

        [MaxLength(255)] public string UrlShown { get; set; }

        [MaxLength(50)] public string NationGeo { get; set; }
        public int NationId { get; set; }

        public int UserId { get; set; }
        public int GroupId { get; set; }
        public int CompanyId { get; set; }
        public int OemId { get; set; }
        [JsonIgnore] public UrlDetails UrlDetails { get; set; }
        [NotMapped]
        public UrlDataJson Details => UrlDetails?.Detail;

        [NotMapped]
        public List<EmployeeJson> Employees => EmployeeDetails?.Employees;
        [JsonIgnore] public EmployeeDetails EmployeeDetails { get; set; }
    }

    [Owned]
    public class UrlDetails
    {
        [Comment("页面信息原始json")] public string DetailJson { get; set; }

        [NotMapped]
        public UrlDataJson Detail
        {
            get => JsonConvert.DeserializeObject<UrlDataJson>(DetailJson);
            set => DetailJson = JsonConvert.SerializeObject(value);
        }

        public DateTime UpdatedAt { get; set; }
    }

    [Owned]
    public class EmployeeDetails
    {
        [Comment("页面信息原始json")] public string EmployeeJson { get; set; }

        [NotMapped]
        public List<EmployeeJson> Employees
        {
            get => JsonConvert.DeserializeObject<List<EmployeeJson>>(EmployeeJson);
            set => EmployeeJson = JsonConvert.SerializeObject(value);
        }

        public DateTime UpdatedAt { get; set; }
    }
}